<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>

        #box{
            width: 100px;
            height: 100px;
            background-color: hotpink;
            position: absolute;
        }
    </style>
</head>
<body>
    <div id="box">

    </div>
    <script>
        // 获取元素
        var box = document.querySelector('#box')
        // 设置点击按下事件
        box.onmousedown = function(){
          

            // 设置移动事件
            window.onmousemove = function(e){
               
                // 处理事件对象兼容
                e = e || window.event
                
                var x = e.clientX - 50
                var y = e.clientY - 50
                // 边界判断
                if (x >= document.documentElement.clientWidth - box.offsetWidth) {
                    x = document.documentElement.clientWidth - box.offsetWidth
             }
                if (y >= document.documentElement.clientHeight - box.offsetHeight) {
                    y = document.documentElement.clientHeight - box.offsetHeight
             }
                if (x <= 0) {
                    x = 0
            }
                if (y <= 0) {
                    y = 0
            }
            // 给box设置top，left值
                box.style.top = y + 'px'
                box.style.left = x + 'px'
            }
            
        }
        // 添加抬起事件
        window.onmouseup = function(){
            window.onmousemove = ''
        }


    </script>
</body>
</html>